# /usr/bin/env python3.6
# -*- encoding: utf-8 -*-
"""
@File    : api.py
@Time    : 2020/2/4 0004 14:50
@Author  : zhangbing
@Email   : 18829172841@163.com
@Software: PyCharm
"""
from flask import request
from flask_restful import Resource, abort
from flask_restful import fields, marshal_with, marshal, reqparse

parser = reqparse.RequestParser()  # 实例化配置

parser.add_argument('g_name', type=str,
                    help="Plase  input  name")  # 此处的help是提示信息，required是必选项，若不选择，则会导致出现错误，type是定义类型，其主要作用是进行预校验功能
parser.add_argument('g_price', type=float, help="Plase  input price")
parser.add_argument('mu', action="append")  # 默认获取第一个参数，设置后获取多个参数，使用列表进行封装
parser.add_argument('rname', dest='name')  # 设置key，默认设置为和后端保持一致，可设置为其他相关参数
parser.add_argument("cookie", dest="co", action="append", location=["cookie", "args"])  # location 表示从头部获取数据，
parser.add_argument('User-Agent', dest='ua', location="headers")

from App.models import Goods

goods_fields = {  # 定义data 数据格式
    'g_id': fields.Integer(attribute="id"),
    'g_name': fields.String(attribute="name"),  # 此处的g_name是显示的字段，而name则是数据库中显示的字段
    'g_price': fields.Float(attribute="price"),
    "g_url": fields.Url("api", absolute=True)  # 设置获取到的URL
}
single_goods_fields = {
    "data": fields.Nested(goods_fields),
    "status": fields.Integer,
    "msg": fields.String,
}

single_goods_list = {  # 处理列表数据相关的数据情况
    # "data": fields.Nested(goods_fields),  # 定义数据格式引用格式
    "data": fields.List(fields.Nested(goods_fields)),
    "status": fields.Integer,  # 定义外部数据数据格式
    "msg": fields.String  # 定义返回数据格式
}


class GoodsList(Resource):
    @marshal_with(single_goods_list)
    def get(self, id):
        args = parser.parse_args()
        print(args.get('co'))
        print(args.get('ua'))
        goods = Goods.query.all()
        return {
            "msg": "get  user  success",
            "status": 200,
            "data": goods  # 此处和marshal_with 作用相同
        }

    @marshal_with(single_goods_fields)
    def post(self, id):
        args = parser.parse_args()
        goods = Goods()
        goods.name = args.get('g_name')
        goods.price = args.get('g_price')
        print(args.get('mu'))
        print(args.get('name'))

        if goods.save():
            return {
                "msg": "create add  success",
                "status": 200,
                "data": goods  # 此处是对上述配置文件的处理
            }
        return {
            "msg": "create add  faields",
            "status": 400,
        }

    @marshal_with(single_goods_fields)
    def delete(self, id):
        try:
            good = Goods.query.get(id)
            if good.delete():
                return {
                    "status": 204,
                    "msg": "data delete  success!",
                    "data": good
                }
        except:
            abort(400, message="good  update failed", msg="about  output")  # 此处可对其进行数据输出增加处理

    def put(self, id):
        g_name = request.form.get("name")
        g_price = request.form.get("price")
        goods = Goods.query.get(id)
        goods.name = g_name
        goods.price = g_price

        if not goods.save():
            abort(400, message="good  update failed")  # 修改默认的abort显示
        return {
            "msg": "update sucess",
            "status": 200,
            "data": marshal(goods, goods_fields)
        }

    def patch(self, id):
        g_name = request.form.get("name")
        g_price = request.form.get("price")
        goods = Goods.query.get(id)
        goods.name = g_name or goods.name
        goods.price = g_price or goods.price

        if not goods.save():
            abort(400, message="good  update failed")
        return {
            "msg": "update sucess",
            "status": 200,
            "data": marshal(goods, goods_fields)
        }


if __name__ == "__main__":
    pass
